package com.itheima.controller;

import com.itheima.domain.Order;
import com.itheima.domain.Product;
import com.itheima.domain.User;
import com.itheima.service.OrderService;
import com.itheima.service.ProductService;
import com.itheima.service.UserService;
import com.itheima.utils.ProductUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class OrderController {

    @Autowired
    private ProductService productService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductUtils productUtils;

    @GetMapping("/showAllOrder")
    public String showOrder(
            HttpSession session,
            Model model,
            @RequestParam(required = false) String searchKeyword,
            @RequestParam(defaultValue = "time_desc") String sort,
            @RequestParam(required = false) String action,
            @RequestParam(required = false) String orderId,
            @RequestParam(defaultValue = "1") int page) { // 默认第一页

        // 1. 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null) {
            session.setAttribute("error", "请先登录账号!");
            return "redirect:/login";
        }

        //订单详情的判断及显示
        if ("detail".equals(action) && orderId != null) {
            Order order = orderService.findOrderById(Integer.parseInt(orderId));
            model.addAttribute("order", order);
            return "showOrder";
        }

        // 2. 获取该用户所有订单
        List<Order> allOrders = orderService.findOrderList(user.getUserId());
        session.setAttribute("productUtils", productUtils);

        //根据关键词过滤订单项
        if (searchKeyword != null && !searchKeyword.trim().isEmpty()) {
            allOrders = allOrders.stream()
                    .filter(order -> {
                        Product product = productService.findProductById(order.getProductId());
                        return order.getOrderNumber().toLowerCase().contains(searchKeyword.toLowerCase()) ||
                                (product != null &&
                                        (product.getTitle().toLowerCase().contains(searchKeyword.toLowerCase()) ||
                                                product.getDescription().toLowerCase().contains(searchKeyword.toLowerCase())));
                    })
                    .collect(Collectors.toList());
        }

        int orderQuantity = allOrders.size();

        //排序
        switch (sort) {
            case "time_asc":
                Collections.sort(allOrders, Comparator.comparing(Order::getCreateTime));
                break;
            case "price_asc":
                Collections.sort(allOrders, Comparator.comparing(Order::getPrice));
                break;
            case "price_desc":
                Collections.sort(allOrders, Comparator.comparing(Order::getPrice).reversed());
                break;
            case "time_desc":
            default:
                Collections.sort(allOrders, Comparator.comparing(Order::getCreateTime).reversed());
                break;
        }

        // 3. 计算分页参数
        int pageSize = 2; // 每页固定显示2个订单
        int totalPages = (int) Math.ceil((double) allOrders.size() / pageSize);

        // 确保页码有效（不超过范围）
        page = Math.max(1, Math.min(page, totalPages));

        // 4. 截取当前页数据
        int startIndex = (page - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, allOrders.size());
        List<Order> currentPageOrders = allOrders.subList(startIndex, endIndex);

        // 5. 传递参数到前端
        model.addAttribute("sort", sort);
        model.addAttribute("orderList", currentPageOrders); // 当前页的订单
        model.addAttribute("currentPage", page);           // 当前页码
        model.addAttribute("totalPages", totalPages);      // 总页数
        model.addAttribute("orderQuantity", orderQuantity);
        model.addAttribute("searchKeyword", searchKeyword);

        return "showOrder";
    }

    @RequestMapping("/orderCancel")
    public String cancelOrder(@RequestParam(required = false) String orderId,
                              RedirectAttributes redirectAttributes) {
        Order order = orderService.findOrderById(Integer.parseInt(orderId));
        if (order != null) {
            int result = orderService.orderCancel(Integer.parseInt(orderId));
            int resultProduct = productService.uploadProductF1(order.getProductId());
            if (!(result > 0) && !(resultProduct > 0)) {
                redirectAttributes.addFlashAttribute("orderError", "取消订单失败，请重试!");
            } else {
                redirectAttributes.addFlashAttribute("orderSuccess", "订单取消成功!");
            }
        } else {
            redirectAttributes.addFlashAttribute("orderError", "付款失败，请重试!");
        }

        return "redirect:/showAllOrder";
    }

    @RequestMapping("/orderPay")
    public String orderPayment(RedirectAttributes redirectAttributes,
                               @RequestParam("orderId") String orderId) {
        System.out.println(orderId);
        Order order = orderService.findOrderById(Integer.parseInt(orderId));
        if (order != null) {
            int result = orderService.orderPay(new Date(), Integer.parseInt(orderId));
            if (!(result > 0)) {
                redirectAttributes.addFlashAttribute("orderError", "付款失败，请重试!");
            } else {
                redirectAttributes.addFlashAttribute("orderSuccess", "付款成功!");
            }
        } else {
            redirectAttributes.addFlashAttribute("orderError", "付款失败，请重试!");
        }
        return "redirect:/showAllOrder";
    }

    @GetMapping("/orderRefund")
    public String refundOrder(@RequestParam(required = false) String orderId,
                              RedirectAttributes redirectAttributes) {
        Order order = orderService.findOrderById(Integer.parseInt(orderId));
        if (order != null) {
            int result = orderService.orderRefund(Integer.parseInt(orderId));
            int resultProduct = productService.uploadProductF1(order.getProductId());
            if (!(result > 0) && !(resultProduct > 0)) {
                redirectAttributes.addFlashAttribute("orderError", "退款失败，请重试!");
            } else {
                redirectAttributes.addFlashAttribute("orderSuccess", "退款成功!");
            }
        } else {
            redirectAttributes.addFlashAttribute("orderError", "付款失败，请重试!");
        }
        return "redirect:/showAllOrder";
    }

    @GetMapping("/orderEnter")
    public String enterOrder(@RequestParam(required = false) String orderId,
                             RedirectAttributes redirectAttributes) {

        int result = orderService.orderEnter(Integer.parseInt(orderId));
        if (!(result > 0)) {
            redirectAttributes.addFlashAttribute("orderError", "确认失败，请重试!");
        } else {
            redirectAttributes.addFlashAttribute("orderSuccess", "确认成功!");
        }

        return "redirect:/showAllOrder";
    }

    @GetMapping("/orderDelete")
    public String deleteOrder(@RequestParam(required = false) String orderId,
                              RedirectAttributes redirectAttributes) {
        int result = orderService.orderDelete(Integer.parseInt(orderId));
        if (!(result > 0)) {
            redirectAttributes.addFlashAttribute("orderError", "删除失败，请重试!");
        } else {
            redirectAttributes.addFlashAttribute("orderSuccess", "删除订单成功!");
        }
        return "redirect:/showAllOrder";
    }

    @RequestMapping("/orderEdit")
    public String orderEdit(Model model,
                            RedirectAttributes redirectAttributes,
                            @RequestParam(required = false) String orderId) {
        Order order = orderService.findOrderById(Integer.parseInt(orderId));
        Product product = productService.findProductById(order.getProductId());
        User buyer = userService.findUserById(order.getBuyerId());
        User seller = userService.findUserById(order.getSellerId());
        if (order == null || product == null || buyer == null || seller == null) {
            redirectAttributes.addFlashAttribute("orderEditError", "修改订单失败！");
            return "redirect:/showOrder?action=detail&orderId=" + orderId;
        }
        model.addAttribute("orderEdit", order);
        model.addAttribute("productEdit", product);
        model.addAttribute("buyerEdit", buyer);
        model.addAttribute("sellerEdit", seller);
        return "confirmOrder";
    }

    @PostMapping("/orderEdit")
    public String orderEdit(RedirectAttributes redirectAttributes,
                            @RequestParam(defaultValue = "0") int orderIdEdit,
                            @RequestParam(required = false) String receiverNameEdit,
                            @RequestParam(required = false) String phoneEdit,
                            @RequestParam(required = false) String editAddress,
                            @RequestParam(required = false) String editHintInfo) {

        Order order = orderService.findOrderById(orderIdEdit);
        int result = 0;
        if (order != null) {
            result = orderService.editOrder(phoneEdit, editAddress, editHintInfo, orderIdEdit);
        }
        if (result > 0) {
            System.out.println(order.getBuyerId());
            userService.setUserAddress(editAddress, order.getBuyerId());
            userService.setUserPhone(phoneEdit, order.getBuyerId());
            redirectAttributes.addFlashAttribute("orderEditSuccess", "修改订单成功！");
        } else {
            redirectAttributes.addFlashAttribute("orderEditError", "修改订单失败！");
        }

        return "redirect:/showAllOrder?action=detail&orderId=" + orderIdEdit;
    }

    @GetMapping("/confirmOrder")
    public String buyProducts(HttpSession session,
                              Model model,
                              RedirectAttributes redirectAttributes,
                              @RequestParam(defaultValue = "0") int productId) {
        User buyer = (User) session.getAttribute("user");
        if (buyer == null) {
            session.setAttribute("error", "请先登录账号!");
            return "redirect:/login";
        }
        Product product = productService.findProductById(productId);
        if (product == null || buyer.getUserId() == product.getUserId()) {
            redirectAttributes.addFlashAttribute("errorInfo", "不可购买自己的商品!");
            return "redirect:/showAllProducts";
        }
        User seller = userService.findUserById(product.getUserId());
        model.addAttribute("product", product);
        model.addAttribute("seller", seller);
        model.addAttribute("productId", productId);
        model.addAttribute("buyer", buyer);

        return "confirmOrder";
    }

        @PostMapping("/confirmOrder")
        public String confirmOrder(HttpSession session,
                                   RedirectAttributes redirectAttributes,
                                   Order order,
                                   @RequestParam(defaultValue = "0") int productId) {
            User buyer = (User) session.getAttribute("user");
            if (buyer == null) {
                session.setAttribute("error", "请先登录账号!");
                return "redirect:/login";
            }

            Product product = productService.findProductById(productId);
            if (product == null) {
                return "error";
            }

            if (product.getStatus() != 1) {
                redirectAttributes.addFlashAttribute("errorInfo", "不可购买已售出或下架的商品！");
                return "redirect:/showAllProducts";
            }

            User seller = userService.findUserById(product.getUserId());

            // 1. 设置订单信息
            order.setBuyerId(buyer.getUserId());
            order.setSellerId(product.getUserId());
            order.setPrice(product.getPrice());
            order.setStatus(0);
            order.setCreateTime(new Date());
            order.setBuyerPhone(buyer.getPhone());
            order.setSellerPhone(seller.getPhone());

            // 2. 生成订单号
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String timeStr = sdf.format(new Date());
            Random random = new Random();
            int randomNum = random.nextInt(9000) + 1000;
            String orderNumber = "ORDER" + timeStr + randomNum + buyer.getUserId();
            order.setOrderNumber(orderNumber);

            // 3. 插入订单
            int insertResult = orderService.insertOrderWithTimeout(order, 30);

            if (insertResult > 0) {
                userService.setUserAddress(order.getAddress(), buyer.getUserId());
                userService.setUserPhone(order.getBuyerPhone(), buyer.getUserId());
                productService.soldProductById(order.getProductId());
                redirectAttributes.addFlashAttribute("success", true);
                redirectAttributes.addFlashAttribute("message", "订单提交成功（1分钟内未支付将自动取消）");

                Order order1 = orderService.findOrderByOrderNumber(orderNumber);

                return "redirect:/confirmOrder?productId=" + order.getProductId() + "&orderId=" + order1.getOrderId();
            } else {
                redirectAttributes.addFlashAttribute("errorInfo", "订单提交失败!");
                redirectAttributes.addFlashAttribute("success", false);
                return "redirect:/showAllProducts";
            }

        }
}
